import 'dart:math';

import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:hero_back/study/flutter_game_flame/day001/component.dart';

mixin Liveable on PositionComponent {
  final Paint outlinePaint = Paint();
  final Paint fillPaint = Paint();
  late double lifePoint;
  late double currentLife;
  final TextStyle defaultTextStyle = const TextStyle(fontSize: 10, color: Colors.green);
  late final TextComponent text;
  final double offsetY = 20;
  final double widthRadio = 0.8;
  final double lifeBarHeight = 8;
  late final DamageText damageText;

  void initPaint({
    required double lifePoint,
    Color lifeColor = Colors.red,
    Color outlineColor = Colors.white,
  }) {
    outlinePaint
      ..color = outlineColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;
    fillPaint.color = lifeColor;
    this.lifePoint = lifePoint;
    currentLife = lifePoint;

    ///生命值文字
    text = TextComponent(textRenderer: TextPaint(style: defaultTextStyle));
    updateLifeText();
    double y = -(offsetY + text.height + 2);
    double x = (size.x / 2) * (1 - widthRadio);
    // text.add(RectangleHitbox()..debugMode = true);
    text.position = Vector2(x, y);
    add(text);

    damageText = DamageText();
    add(damageText);
  }

  double get progress => currentLife / lifePoint;

  @override
  void render(Canvas canvas) {
    super.render(canvas);
    Rect rect = Rect.fromCenter(
      center: Offset(size.x / 2, lifeBarHeight / 2 - offsetY),
      width: size.x * widthRadio,
      height: lifeBarHeight,
    );
    Rect lifeRect = Rect.fromPoints(
      rect.topLeft + Offset(rect.width * (1 - progress), 0),
      rect.bottomRight,
    );

    canvas.drawRect(lifeRect, fillPaint);
    canvas.drawRect(rect, outlinePaint);
  }

  ///损失血量
  void loss(double point) {
    currentLife -= point;
    updateLifeText();
    if (currentLife <= 0) {
      currentLife = 0;
      onDied();
    }
    // damageText.addDamage(50);
    damageText.addDamage(40, isCrit: Random().nextBool());
  }

  void onDied() {}

  void updateLifeText() {
    text.text = 'Hp ${currentLife.toInt()}';
  }
}
